package com.example.translationapp.util;

import com.example.translationapp.Constant;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by liuzhao.futrue on 2018/9/12.
 */

public class NetUtils {

    private static OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    /**
     * 执行Post网络请求
     *
     * @param url
     * @param query
     * @return
     * @throws IOException
     */
    public static String executePost(String query) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        String salt = SignUtils.getRandomInt(10);
        builder.add("q", query);
        builder.add("from", "auto");
        builder.add("to", "en");
        builder.add("appid", Constant.APPID);
        builder.add("salt", salt);
        builder.add("sign", SignUtils.getSign(Constant.APPID, query, salt, Constant.KEY));

        Request request = new Request.Builder()
                .url(Constant.HTTP_API_FANYI_BAIDU_COM_API_TRANS_VIP_TRANSLATE)
                .post(builder.build())
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 执行Get网络请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String exectueGet(String url) throws IOException {
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}
